﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Text;
using System.Xml;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

///<summary>
/// XMLHelper XML文档操作基类(包装各类方法)
/// by:IT刀客
/// Date:2017-04-29
///</summary>
public class XMLHelper
{
    public XMLHelper()
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    }


#region XML文档节点查询和读取
    ///<summary>
    /// 选择匹配XPath表达式的第一个节点XmlNode.
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
    ///<returns>返回XmlNode</returns>
    public static XmlNode GetXmlNodeByXpath(string xmlFileName, string xpath)
    {
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            return xmlNode;
        }
        catch (Exception ex)
        {
            return null;
            throw ex; //异常处理信息
        }
    }

    ///<summary>
    /// 选择匹配XPath表达式的节点列表XmlNodeList.
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
    ///<returns>返回XmlNodeList</returns>
    public static XmlNodeList GetXmlNodeListByXpath(string xmlFileName, string xpath)
    {
        XmlDocument xmlDoc =new XmlDocument();

        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath);
            return xmlNodeList;
        }
        catch (Exception ex)
        {
            return null;
            throw ex; //异常处理信息
        }
    }

    ///<summary>
    /// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
    ///<returns>返回xmlAttributeName</returns>
    public static XmlAttribute GetXmlAttribute(string xmlFileName, string xpath, string xmlAttributeName)
    {
        string content =string.Empty;
        XmlDocument xmlDoc =new XmlDocument();
        XmlAttribute xmlAttribute =null;
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode !=null)
            {
                if (xmlNode.Attributes.Count >0)
                 {
                    xmlAttribute = xmlNode.Attributes[xmlAttributeName];
                 }
            }
         }
         catch (Exception ex)
             {
                throw ex; //异常处理信息
             }
        return xmlAttribute;
    }
#endregion

#region XML文档创建和节点或属性的添加、修改
    ///<summary>
    /// 创建一个XML文档
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="rootNodeName">XML文档根节点名称(须指定一个根节点名称)</param>
    ///<param name="version">XML文档版本号(必须为:"1.0")</param>
    ///<param name="encoding">XML文档编码方式</param>
    ///<param name="standalone">该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool CreateXmlDocument(string xmlFileName, string rootNodeName, string version, string encoding, string standalone)
    {
        bool isSuccess =false;
        try
        {
            XmlDocument xmlDoc =new XmlDocument();
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version, encoding, standalone);
            XmlNode root = xmlDoc.CreateElement(rootNodeName);
            xmlDoc.AppendChild(xmlDeclaration);
            xmlDoc.AppendChild(root);
            xmlDoc.Save(xmlFileName);
            isSuccess =true;
        }
        catch (Exception ex)
        {
            throw ex; //异常处理信息
        }
        return isSuccess;
    }

    ///<summary>
    /// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
    ///<param name="innerText">节点文本值</param>
    ///<param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
    ///<param name="value">属性值</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool CreateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText, string xmlAttributeName, string value)
    {
        bool isSuccess =false;
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode !=null)
            {
                //存不存在此节点都创建
                XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                subElement.InnerXml = innerText;

                //如果属性和值参数都不为空则在此新节点上新增属性
                if (!string.IsNullOrEmpty(xmlAttributeName) &&!string.IsNullOrEmpty(value))
                {
                    XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
                    xmlAttribute.Value = value;
                    subElement.Attributes.Append(xmlAttribute);
                }

                xmlNode.AppendChild(subElement);
            }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            isSuccess =true;
        }
        catch (Exception ex)
        {
            throw ex; //异常处理
        }
        return isSuccess;
    }

    ///<summary>
    /// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
    ///<param name="innerText">节点文本值</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText)
    {
        bool isSuccess =false;
        bool isExistsNode =false;//标识节点是否存在
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode !=null)
            {
                //遍历xpath节点下的所有子节点
                foreach (XmlNode node in xmlNode.ChildNodes)
                {
                    if (node.Name.ToLower() == xmlNodeName.ToLower())
                    {
                        //存在此节点则更新
                        node.InnerXml = innerText;
                        isExistsNode =true;
                        break;
                    }
                }
                if (!isExistsNode)
                {
                    //不存在此节点则创建
                    XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                    subElement.InnerXml = innerText;
                    xmlNode.AppendChild(subElement);
                }
            }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            isSuccess =true;
        }
        catch (Exception ex)
        {
            throw ex; //异常处理
        }
        return isSuccess;
    }

    ///<summary>
    /// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建)
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
    ///<param name="value">属性值</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool CreateOrUpdateXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string value)
    {
        bool isSuccess =false;
        bool isExistsAttribute =false;//标识属性是否存在
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode !=null)
            {
                //遍历xpath节点中的所有属性
                foreach (XmlAttribute attribute in xmlNode.Attributes)
                {
                    if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
                    {
                        //节点中存在此属性则更新
                        attribute.Value = value;
                        isExistsAttribute =true;
                        break;
                    }
                 }
                if (!isExistsAttribute)
                {
                    //节点中不存在此属性则创建
                    XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
                    xmlAttribute.Value = value;
                    xmlNode.Attributes.Append(xmlAttribute);
                }
            }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            isSuccess =true;
        }
        catch (Exception ex)
        {
        throw ex; //异常处理
        }
        return isSuccess;
}
#endregion


#region XML文档节点或属性的删除
    ///<summary>
    /// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除)
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool DeleteXmlNodeByXPath(string xmlFileName, string xpath)
    {
        bool isSuccess =false;
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode !=null)
            {
                //删除节点
                xmlNode.ParentNode.RemoveChild(xmlNode);
             }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            isSuccess =true;
         }
        catch (Exception ex)
        {
            throw ex; //异常处理
        }
        return isSuccess;
    }

    ///<summary>
    /// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<param name="xmlAttributeName">要删除的xmlAttributeName的属性名称</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool DeleteXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName)
    {
        bool isSuccess =false;
        bool isExistsAttribute =false;
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            XmlAttribute xmlAttribute =null;
            if (xmlNode !=null)
            {
                //遍历xpath节点中的所有属性
                foreach (XmlAttribute attribute in xmlNode.Attributes)
                {
                    if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
                    {
                        //节点中存在此属性
                        xmlAttribute = attribute;
                        isExistsAttribute =true;
                        break;
                    }
                }
                if (isExistsAttribute)
                    {
                        //删除节点中的属性
                        xmlNode.Attributes.Remove(xmlAttribute);
                    }
            }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            isSuccess =true;
        }
        catch (Exception ex)
        {
            throw ex; //异常处理
        }
        return isSuccess;
    }

    ///<summary>
    /// 删除匹配XPath表达式的第一个节点中的所有属性
    ///</summary>
    ///<param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
    ///<param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
    ///<returns>成功返回true,失败返回false</returns>
    public static bool DeleteAllXmlAttributeByXPath(string xmlFileName, string xpath)
    {
        bool isSuccess =false;
        XmlDocument xmlDoc =new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode !=null)
            {
                //遍历xpath节点中的所有属性
                xmlNode.Attributes.RemoveAll();
            }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            isSuccess =true;
        }
        catch (Exception ex)
        {
            throw ex; //异常处理
        }
        return isSuccess;
    }
    #endregion
    #region 系统登录
    /// <summary>
    /// 系统登录方法：
    /// </summary>
    /// <param name="uName">uName传入的用户名字符串</param>
    /// <param name="Pwd">Pwd传入的密码字符串</param>
    /// <returns>返回登录后获取的数据数组</returns>
    public static string LoginResult(string uName,string Pwd)
    {
        string ResultStr = ""; //定义返回变量
        int uId = 0;//用户ID
        int lgCount = 0; //用户登录次数
        int RoleId = 0;
        string UserHead = "";//用户头像

        #region //验证登录是否存在
        DataSet dst = rds("App_Data\\TbUser.xml");
        for(int i=0; i< dst.Tables[0].Rows.Count; i++)
        {
            if(dst.Tables[0].Rows[i]["UserName"].ToString() == uName)
            {
                uId = int.Parse(dst.Tables[0].Rows[i]["UserId"].ToString());
                uName = dst.Tables[0].Rows[i]["UserName"].ToString();
                Pwd = dst.Tables[0].Rows[i]["UserPwd"].ToString();
                RoleId = int.Parse(dst.Tables[0].Rows[i]["UserRoleId"].ToString());
                UserHead = dst.Tables[0].Rows[i]["UserHead"].ToString();
                break;
            }
        }
        #endregion
        #region // 读写日志文件
        //加载日志XML
        XmlDocument xmlDoc = new XmlDocument();
        string roadLog = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\UserLog.xml";
        xmlDoc.Load(roadLog);
        //获取UserTable节点的所有子节点
        //XmlNodeList LogNlst = xmlDoc.SelectSingleNode("UserLog").ChildNodes;
        XmlNode xmlNd = xmlDoc.SelectSingleNode("UserLog//UserInfo[@uName='" + uName + "']");
         //遍历日志XML所有子节点
        foreach (XmlNode xnd in xmlNd.ChildNodes)
        {
            switch (xnd.Name)
            {
                case "LoginCount":
                    lgCount = int.Parse(xnd.InnerText);
                    xnd.InnerText = (lgCount + 1).ToString();
                    break;
                case "Locked":
                    xnd.InnerText = "0";
                    break;
            }
        }
        try
        {
            xmlDoc.Save(roadLog);
        }
        catch
        {

        }
        #endregion
        ResultStr = uId + "," + uName + "," + Pwd + "," + RoleId + "," + UserHead + ","+ (lgCount+1);
        return ResultStr;
    }
    #endregion
    ///<summary>
    /// 检查用户是否被锁定
    /// </summary>
    ///<param name="uName">uName传入的用户名字符串</param>
    public static bool locked(string uName)
    {
        bool IsLocked = false;
        XmlDocument xmlDoc = new XmlDocument();
        string RoadStr = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\UserLog.xml";

        xmlDoc.Load(RoadStr); //加载xml文件
        //获取UserTable节点的所有子节点
        XmlNodeList nodeList = xmlDoc.SelectSingleNode("UserLog").ChildNodes;

        //遍历所有子节点
        foreach (XmlNode xn in nodeList)
        {
            XmlElement xe = (XmlElement)xn; //将子节点类型转换为XmlElement类型

            if (xe.GetAttribute("uName") == uName)//如果uName属性值为用户传入用户名
            {
                XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点

                foreach (XmlNode xn1 in nls)//遍历
                {
                    XmlElement Uxe = (XmlElement)xn1; //转换类型

                    if (Uxe.Name == "Locked")
                    {
                        if(Uxe.InnerText == "1")
                        {
                            IsLocked = true;
                        } 
                    }
                }
                break;
            }
        }
        return IsLocked;
    }

    ///<summary>
    /// 以流模式读XML文件,获取符合条件的节点信息（用户信息）：
    /// <param name="NodeAttribute">节点属性NodeAttribute</param>
    /// <returns>string字符串</returns>
    /// </summary>
    public static string getNodeStr(string NodeAttribute)
    {
        int uId = 0;
        string Pwd = "";
        int RoleId = 0;
        string reString = "";
        string uHeadImg = "";
        string UserName = "";
        string LoginCount = "";
        string Locked = null;
        //以流模式读入XML文件，声明一个reader
        XmlTextReader xmlReader = new XmlTextReader(AppDomain.CurrentDomain.BaseDirectory + @"/App_Data//BaseData.xml");
        //xmlReader.MoveToElement();
        
        //如果获取到符合条件的节点 UserData节点的属性值为uName，且uName的值为传入的参数值
        while (xmlReader.Read())
        {
            xmlReader.ReadToFollowing("UserData");
            string uNameAttribute = xmlReader.GetAttribute("uName");
            if (xmlReader.GetAttribute("uName") == NodeAttribute)
            {
                if (xmlReader.NodeType == XmlNodeType.Element)
                {
                    //xmlReader.Name == "UserData" && xmlReader.GetAttribute("uName") == NodeAttribute
                    switch (xmlReader.Name)
                    {
                        case "UserId":
                            uId = int.Parse(xmlReader.ReadElementString().Trim());
                            break;
                        case "UserHead":
                            uHeadImg = xmlReader.ReadElementString().Trim();
                            break;
                        case "UserPwd":
                            Pwd = xmlReader.ReadElementString().Trim();
                            break;
                        case "UserRoleId":
                            RoleId = int.Parse(xmlReader.ReadElementString().Trim());
                            break;
                        case "UserName":
                            UserName = xmlReader.ReadElementString().Trim();
                            break;
                        case "LoginCount":
                            LoginCount = xmlReader.ReadElementString().Trim();
                            break;
                    }
                    if (Locked != null && UserName == NodeAttribute)
                    {
                        reString = uId + "," + Pwd + "," + RoleId + "," + UserName + "," + LoginCount + "," + uHeadImg;
                        break;
                    }
                 }
            }  
        }
        xmlReader.Close();
        return reString;
    } 

    ///<summary>
    ///以文件流模式读取整个XML文档内容并转换为DataSet
    ///</summary>
    public static DataSet rds(string XmlFile)
    {
        DataSet ds = new DataSet();
        string RoadStr = System.AppDomain.CurrentDomain.BaseDirectory + XmlFile;
        FileStream fs = new FileStream(RoadStr, FileMode.Open, FileAccess.Read);
        ds.ReadXml(fs);

        fs.Close();
        return ds;
    }

    ///<summary>
    /// 在DataSet中对数据集分页：
    /// <param name="ds">传入的DataSet数据集</param>
    /// <param name="PageIndex">分页页数</param>
    /// <param name="PageSize">页记录数</param>
    /// </summary>
    public static DataTable dtb(DataSet ds,int PageIndex,int PageSize)
    {
        DataTable dt = new DataTable();
        dt = ds.Tables[0].Clone();
        int RecdStart = (PageIndex - 1) * PageSize;
        int RecdEnd = PageIndex * PageSize;
        //int TotalPage = 1;
        //if(ds.Tables[0].Rows.Count>0)
        //{
        //    TotalPage = ds.Tables[0].Rows.Count / PageSize + 1;
        //}
        if (RecdStart <= ds.Tables[0].Rows.Count)
        {
            for(int getRecd = RecdStart; getRecd< RecdEnd && getRecd< ds.Tables[0].Rows.Count; getRecd++)
            {
                dt.ImportRow(ds.Tables[0].Rows[getRecd]);
            }
        }
        ds.Dispose();
        return dt;
    }

    ///<summary>
    ///当前用户在Session周期内锁定系统：
    ///<param name="uName">uName传入的用户名字符串</param>
    ///<returns>布尔值</returns>
    ///</summary>
    public static bool IsLocked(string uName)
    {
        bool locked = false;
        XmlDocument xmlDoc = new XmlDocument();
        string roadLog = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\UserLog.xml";
        xmlDoc.Load(roadLog); //加载xml文件
        //获取UserTable节点的所有子节点
        XmlNodeList nodeList = xmlDoc.SelectSingleNode("UserLog").ChildNodes;
        //遍历所有子节点
        foreach (XmlNode xn in nodeList)
        {
            XmlElement xe = (XmlElement)xn; //将子节点类型转换为XmlElement类型

            if (xe.GetAttribute("uName") == uName)//如果uName属性值为用户传入用户名
            {
                XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点

                foreach (XmlNode xn1 in nls)//遍历
                {
                    XmlElement Uxe = (XmlElement)xn1; //转换类型

                    if (Uxe.Name == "Locked")
                    {
                        Uxe.InnerText = "1";
                        locked = true;
                    }
                }
                break;
            }
        }
        try
        {
            xmlDoc.Save(roadLog);
        }
        catch(Exception ex)
        {
            throw ex;
        }
       
        return locked;
    }

    ///<summary>
    /// 修改用户密码：
    /// <param name="uName">传入用户名</param>
    /// <paramref name="Pwd">传入用户新密码</paramref>
    /// </summary>
    /// <returns>返回成功与否的布尔值</returns>
    public static bool IsPwd(string uName,string Pwd)
    {
        bool IsUp = false;

        XmlDocument xmlDoc = new XmlDocument();
        string roadLog = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\BaseData.xml";
        xmlDoc.Load(roadLog); //加载xml文件
        //获取UserTable节点的所有子节点
        XmlNodeList nodeList = xmlDoc.SelectSingleNode("UserTable").ChildNodes;
        //遍历所有子节点
        foreach (XmlNode xn in nodeList)
        {
            XmlElement xe = (XmlElement)xn; //将子节点类型转换为XmlElement类型

            if (xe.GetAttribute("uName") == uName)//如果uName属性值为用户传入用户名
            {
                XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点

                foreach (XmlNode xn1 in nls)//遍历
                {
                    XmlElement Uxe = (XmlElement)xn1; //转换类型

                    switch (Uxe.Name)
                    {
                        case "UserPwd":
                            Uxe.InnerText = Pwd;
                            break;
                    }
                }
                break;
            }
        }
        try
        {
            xmlDoc.Save(roadLog);
            IsUp = true;
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return IsUp;
    }

    ///<summary>
    ///以流模式写XML文件，修改系统配置
    ///<param name="fileName">传入XML文件名</param>
    ///</summary>
    public static bool WriteXml(string fileName, string systemName,string uName, string User,string hstIp, string pwd)
    {
        bool rslt = true;
        fileName = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\"+ fileName;
        XmlTextWriter xmlWriter = new XmlTextWriter(fileName, null);
        xmlWriter.Formatting = Formatting.Indented;

        xmlWriter.WriteStartDocument();
        xmlWriter.WriteStartElement("SystemParam");
        xmlWriter.WriteElementString("systemName", systemName);
        xmlWriter.WriteElementString("User", uName);
        xmlWriter.WriteElementString("softVertion", "1.1");
        xmlWriter.WriteElementString("techSupport", "IT刀客");
        xmlWriter.WriteElementString("sessionTime", "30");

        xmlWriter.WriteElementString("techMobile", "15986735685");
        xmlWriter.WriteElementString("techQQ", "562318426");
        xmlWriter.WriteElementString("techEmai", "kevin1105@qq.com");
        xmlWriter.WriteElementString("hostIp", hstIp);
        xmlWriter.WriteElementString("DbUser", User);
        xmlWriter.WriteElementString("DbPwd",pwd);
        xmlWriter.WriteEndElement();
        xmlWriter.WriteEndDocument();

        xmlWriter.Flush();
        xmlWriter.Close();
        return rslt;
    }

    ///<summary>
    /// 向XML文件中插入一个完整的节点：添加用户--
    /// <param name="fileName"></param>
    /// </summary>
    public static int AddUserNode(string fileName,string[] NodeList)
    {
        int Success = 1;
        string roadUser = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
        string roadLog = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\UserLog.xml";
        DataSet dst = rds(fileName);
        for(int i=0;i< dst.Tables[0].Rows.Count;i++)
        {
            if(dst.Tables[0].Rows[i]["UserName"].ToString() == NodeList[0])
            {
                Success = 0;//用户名已存在
            }
        }
        int recdId = dst.Tables[0].Rows.Count;
        recdId = recdId + 1;
        if (Success == 1)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(roadUser);

            XmlNode root = xmlDoc.SelectSingleNode("UserTable");//查找<UserTable>根节点  
            XmlElement rxe = xmlDoc.CreateElement("UserData");//创建一个<UserData>节点  
            rxe.SetAttribute("UId", recdId.ToString());//设置该节点UId属性    
            rxe.SetAttribute("uName", NodeList[0]);//设置该节点uName属性  

            XmlElement xesub = xmlDoc.CreateElement("UserId");
            xesub.InnerText = recdId.ToString();//设置文本节点  
            rxe.AppendChild(xesub);//添加到<UserData>节点中  
            XmlElement xesub2 = xmlDoc.CreateElement("UserName");
            xesub2.InnerText = NodeList[0];
            rxe.AppendChild(xesub2); 

            XmlElement xeRname = xmlDoc.CreateElement("RealName");
            xeRname.InnerText = NodeList[6];
            rxe.AppendChild(xeRname); //添加真实姓名节点

            XmlElement xeCno = xmlDoc.CreateElement("CardNo"); //添加身份证节点
            xeCno.InnerText = NodeList[7];
            rxe.AppendChild(xeCno);

            XmlElement uHead = xmlDoc.CreateElement("UserHead");
            uHead.InnerText = NodeList[14];
            rxe.AppendChild(uHead);

            XmlElement UPwd = xmlDoc.CreateElement("UserPwd");
            UPwd.InnerText = NodeList[1];
            rxe.AppendChild(UPwd);

            XmlElement xmlRole = xmlDoc.CreateElement("UserRoleId");
            xmlRole.InnerText = NodeList[2];
            rxe.AppendChild(xmlRole);

            XmlElement xmlName = xmlDoc.CreateElement("UserRoleName");
            xmlName.InnerText = NodeList[3];
            rxe.AppendChild(xmlName);

            XmlElement xmlMenu = xmlDoc.CreateElement("UserMenu");
            xmlMenu.InnerText = "";
            rxe.AppendChild(xmlMenu);

            XmlElement xmlDeptId = xmlDoc.CreateElement("DeptId");
            xmlDeptId.InnerText = NodeList[4];
            rxe.AppendChild(xmlDeptId);

            XmlElement xmlDept = xmlDoc.CreateElement("Dept");
            xmlDept.InnerText = NodeList[5];
            rxe.AppendChild(xmlDept);

            XmlElement xmlPosition = xmlDoc.CreateElement("Position");
            xmlPosition.InnerText = NodeList[8];
            rxe.AppendChild(xmlPosition);

            XmlElement xmlMobile = xmlDoc.CreateElement("Mobile");
            xmlMobile.InnerText = NodeList[9];
            rxe.AppendChild(xmlMobile);

            XmlElement xmlEntryDate = xmlDoc.CreateElement("EntryDate");
            xmlEntryDate.InnerText = NodeList[10];
            rxe.AppendChild(xmlEntryDate);
            XmlElement xmlStaffDate = xmlDoc.CreateElement("StaffDate");
            xmlStaffDate.InnerText = NodeList[11];
            rxe.AppendChild(xmlStaffDate);
            XmlElement xmlQQ = xmlDoc.CreateElement("QQ");
            xmlQQ.InnerText = NodeList[12];
            rxe.AppendChild(xmlQQ);
            XmlElement xmlEmail = xmlDoc.CreateElement("Email");
            xmlEmail.InnerText = NodeList[13];
            rxe.AppendChild(xmlEmail);

            root.AppendChild(rxe);//添加到<UserTable>节点中  
            xmlDoc.Save(roadUser);

            //写日志文件
            XmlDocument xmlDocLg = new XmlDocument();
            xmlDocLg.Load(roadLog);
            XmlNode rootNode = xmlDocLg.SelectSingleNode("UserLog");//查找<UserTable>根节点  
            XmlElement xmlel = xmlDocLg.CreateElement("UserInfo");//创建一个<UserData>节点
            xmlel.SetAttribute("Uid", recdId.ToString());//设置该节点Uid属性       
            xmlel.SetAttribute("uName", NodeList[0]);//设置该节点uName属性  

            XmlElement SubNodeUid = xmlDocLg.CreateElement("UserId");
            SubNodeUid.InnerText = recdId.ToString();//设置文本节点  
            xmlel.AppendChild(SubNodeUid);//添加到<UserInfo>节点中 

            XmlElement SubNodeUname = xmlDocLg.CreateElement("UserName");
            SubNodeUname.InnerText = NodeList[0];//设置文本节点  
            xmlel.AppendChild(SubNodeUname);//添加到<UserInfo>节点中 

            XmlElement SubNodeLgCount = xmlDocLg.CreateElement("LoginCount");
            SubNodeLgCount.InnerText = "0";//设置文本节点  
            xmlel.AppendChild(SubNodeLgCount);//添加到<UserInfo>节点中  

            XmlElement SubNodeLocked = xmlDocLg.CreateElement("Locked");
            SubNodeLocked.InnerText = "0";//设置文本节点  
            xmlel.AppendChild(SubNodeLocked);//添加到<UserInfo>节点中 

            rootNode.AppendChild(xmlel);
            xmlDocLg.Save(roadLog);
        }

        return Success;
    }
    ///<summary>
    ///修改用户表指定节点及其子节点
    ///<param name="xmlFileName">文件路径</param>
    ///<param name="xpath">xpath表达式</param>
    ///<param name="NodeName">节点名称数组</param>
    ///<param name="innerText">节点值数组</param>
    ///<returns>返回Boolean值成功与否</returns>
    /// </summary>
    public static bool IsUpdateNode(string xmlFileName, string xpath,string[] NodeName,string[] innerText)
    {
        bool IsSuccess = false;
        bool isExistsNode = false;//标识节点是否存在

        XmlDocument xmlDoc = new XmlDocument();
        try
        {
            xmlDoc.Load(xmlFileName); //加载XML文档
            XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
            if (xmlNode != null)
            {
                //遍历xpath节点下的所有子节点
                foreach (XmlNode node in xmlNode.ChildNodes)
                {
                    switch (node.Name)
                    {
                        case "UserHead":
                            node.InnerText = innerText[12];
                            break;
                        case "UserName":
                            node.InnerText = innerText[0];
                            break;
                        case "RealName":
                            node.InnerText = innerText[1];
                            break;
                        case "UserRoleId":
                            node.InnerText = innerText[2];
                            break;
                        case "UserRoleName":
                            node.InnerText = innerText[3];
                            break;
                        case "CardNo":
                            node.InnerText = innerText[4];
                            break;
                        case "DeptId":
                            node.InnerText = innerText[5];
                            break;
                        case "Dept":
                            node.InnerText = innerText[6];
                            break;
                        case "Position":
                            node.InnerText = innerText[7];
                            break;
                        case "Mobile":
                            node.InnerText = innerText[8];
                            break;
                        case "StaffDate":
                            node.InnerText = innerText[9];
                            break;
                        case "QQ":
                            node.InnerText = innerText[10];
                            break;
                        case "Email":
                            node.InnerText = innerText[11];
                            isExistsNode = true;
                            break;
                    }
                    if (isExistsNode)
                    {
                        break;
                    }
                    //if (!isExistsNode)//不存在此节点则创建
                    //{  
                    //    XmlElement subElement = xmlDoc.CreateElement(NodeName[i]);
                    //    subElement.InnerXml = innerText[0];
                    //    xmlNode.AppendChild(subElement);
                    //}
                }   
            }
            xmlDoc.Save(xmlFileName); //保存到XML文档
            IsSuccess = true;
        }
        catch (Exception ex)
        {
            throw ex; //异常处理
        }

        return IsSuccess;
    }

    ///<summary>
    /// 向XML文件中插入一个完整的节点：添加角色--
    /// <param name="fileName"></param>
    /// </summary>
    public static int AddNewRole(string fileName, string[] NodeList)
    {
        int Success = 1;
        string roadUser = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
        DataSet dst = rds(fileName);
        for (int i = 0; i < dst.Tables["RoleData"].Rows.Count; i++)
        {
            if (dst.Tables[0].Rows[i]["roleName"].ToString() == NodeList[0])
            {
                Success = 0;//角色已存在
            }
        }
        int recdId = dst.Tables[0].Rows.Count;
        recdId = recdId + 1;
        if (Success == 1)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(roadUser);

            XmlNode root = xmlDoc.SelectSingleNode("UserRole");//查找<UserRole>根节点  
            XmlElement rxe = xmlDoc.CreateElement("RoleData");//创建一个<RoleData>节点  
            rxe.SetAttribute("rId", recdId.ToString());//设置该节点UId属性    

            XmlElement xesub = xmlDoc.CreateElement("roleId");//添加角色ID
            xesub.InnerText = recdId.ToString();//设置文本节点  
            rxe.AppendChild(xesub);//添加到<RoleData>节点中  

            XmlElement xesub2 = xmlDoc.CreateElement("roleName");//添加角色名
            xesub2.InnerText = NodeList[0];
            rxe.AppendChild(xesub2);

            XmlElement xeRname = xmlDoc.CreateElement("mRoleId");//添加角色主模块ID
            xeRname.InnerText = NodeList[1];
            rxe.AppendChild(xeRname); 

            XmlElement xeCno = xmlDoc.CreateElement("UrlmIcon"); //添加主模块图标
            xeCno.InnerText = NodeList[2];
            rxe.AppendChild(xeCno);

            XmlElement uHead = xmlDoc.CreateElement("mainRole"); //添加主模块名称
            uHead.InnerText = NodeList[3];
            rxe.AppendChild(uHead);

            XmlElement UPwd = xmlDoc.CreateElement("UrlId");//添加子导航菜单ID
            UPwd.InnerText = NodeList[4];
            rxe.AppendChild(UPwd);

            XmlElement xmlRole = xmlDoc.CreateElement("UrlIcon"); //添加子导航（链接）菜单图标
            xmlRole.InnerText = NodeList[5];
            rxe.AppendChild(xmlRole);

            XmlElement xmlName = xmlDoc.CreateElement("roleList"); //添加子导航名称
            xmlName.InnerText = NodeList[6];
            rxe.AppendChild(xmlName);

            XmlElement xmlMenu = xmlDoc.CreateElement("UrlList"); //添加导航URL地址
            xmlMenu.InnerText = NodeList[7];
            rxe.AppendChild(xmlMenu);

            XmlElement xmlDeptId = xmlDoc.CreateElement("operater"); //添加操作人
            xmlDeptId.InnerText = NodeList[8];
            rxe.AppendChild(xmlDeptId);

            XmlElement xmlDept = xmlDoc.CreateElement("addDate"); //添加操作时间
            xmlDept.InnerText = NodeList[9];
            rxe.AppendChild(xmlDept);

            XmlElement xmlPosition = xmlDoc.CreateElement("locked"); //节点是否锁定
            xmlPosition.InnerText = NodeList[10];
            rxe.AppendChild(xmlPosition);

            root.AppendChild(rxe);//添加到<UserRole>节点中  
            xmlDoc.Save(roadUser);
        }
            return Success;
    }

    ///<summary>
    ///向XML文档尾部添加节点及子节点数据
    /// </summary>
    /// 
    public static int AddDeptNode(string fileName, string[] NodeNameList,string[] NodeWorthList,string[] rootNode)
    {
        int success = 1;
        string DeptURI = System.AppDomain.CurrentDomain.BaseDirectory + fileName;//获取要插入节点的XML文件的物理路径
        DataSet dst = rds(fileName);
        int deptId = dst.Tables[rootNode[2]].Rows.Count + 1;
        for (int i = 1; i < deptId-1; i++)
        {
            if (dst.Tables[rootNode[2]].Rows[i][NodeNameList[i]].ToString() == NodeWorthList[i])
            {
                success = 0;//部门已存在
            }
        }
        if (success == 1)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(DeptURI);
            XmlNode root = xmlDoc.SelectSingleNode(rootNode[0]+"/"+ rootNode[1]);//查找<DepartMent>根节点            
            XmlElement rxe = xmlDoc.CreateElement(NodeNameList[0]);//创建一个<RoleData>节点  
            rxe.SetAttribute("Id", deptId.ToString());//设置该节点Id属性 

            XmlElement xeDptId = xmlDoc.CreateElement("DeptId");//添加部门ID节点
            xeDptId.InnerText = deptId.ToString();
            rxe.AppendChild(xeDptId);
            for (int x=2;x< NodeNameList.Length;x++)
            {
                XmlElement xmlelet = xmlDoc.CreateElement(NodeNameList[x]); //添加子节点
                xmlelet.InnerText = NodeWorthList[x];
                rxe.AppendChild(xmlelet);
            }
            root.AppendChild(rxe);//添加到<RoleData>节点中  
            xmlDoc.Save(DeptURI);
        }
        return success;
    }
    ///<summary>
    ///修改用户指定XML文件节点及其子节点
    ///<param name="xmlFileName">文件路径</param>
    ///<param name="xpath">xpath表达式</param>
    ///<param name="NodeName">节点名称数组</param>
    ///<param name="innerText">节点值数组</param>
    ///<returns>返回Boolean值成功与否</returns>
    /// </summary>
    public static int UpdateXmlNode(string xmlFileName, string xpath,string[] NodeName,string[] innerText)
    {
        int IsOk = 0;
        string DeptURI = System.AppDomain.CurrentDomain.BaseDirectory + xmlFileName;//获取要插入节点的XML文件的物理路径
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(DeptURI);
        XmlNode root = xmlDoc.SelectSingleNode(xpath);//查找要写入数据的根节点  

        if (root != null)
        {
            //遍历xpath节点下的所有子节点
            foreach (XmlNode node in root.ChildNodes)
            {
                for (int x = 0; x < NodeName.Length; x++)
                {
                    if (node.Name == NodeName[x])
                    {
                        node.InnerText = innerText[x];
                    }
                }
            }
            try
            {
                xmlDoc.Save(DeptURI);
                IsOk = 1;
            }
            catch(Exception ex)
            {
                throw ex;//捕获异常信息
            }
        }

        return IsOk;
    }
}